var xmlns = "http://www.w3.org/2000/svg";
var svg = document.getElementById('svgMaze');
let win = false;

var drawMap = function () {
        var messageBox = document.createElementNS(xmlns, 'clipPath');
        messageBox.setAttribute('id', 'messageBoxPath');
        var messageBoxRect = document.createElementNS(xmlns, 'rect');
        messageBoxRect.setAttribute('width', 100);
        messageBoxRect.setAttribute('height', 100);
        messageBoxRect.setAttribute('x', 150);
        messageBoxRect.setAttribute('y', 50);
        messageBox.appendChild(messageBoxRect);
        svg.appendChild(messageBox);

        var messageBoxImage = document.createElementNS(xmlns, 'image');
        messageBoxImage.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href',
                './res9/messageBox.png');
        messageBoxImage.setAttribute('id', 'messageBox');
        messageBoxImage.setAttribute('height', 100);
        messageBoxImage.setAttribute('width', 100);
        messageBoxImage.setAttribute('clip-path', 'url(#messageBoxPath)');
        messageBoxImage.setAttribute('x', 150);
        messageBoxImage.setAttribute('y', 50);
        messageBoxImage.setAttribute('opacity', 0);
        svg.appendChild(messageBoxImage);

        var text = document.createElementNS(xmlns, 'text');
        text.setAttribute('id', 'text');
        text.innerHTML = "你好世界";
        text.setAttribute('x', 165);
        text.setAttribute('y', 90);
        text.setAttribute('opacity', 0);
        svg.appendChild(text);
}
drawMap();

function speak(text) {
        if (text === "你好世界") {
                var messageBox = document.getElementById("messageBox");
                messageBox.setAttribute('opacity', 1);
                var text = document.getElementById("text");
                text.setAttribute('opacity', 1);
                win = true;
        }
}

function runButtonClick() {
        var code = Blockly.JavaScript.workspaceToCode(workspace);
        console.log(code);
        Blockly.JavaScript.INFINITE_LOOP_TRAP = null;
        try {
                alert(code);
                eval(code);
                setTimeout(check_win, 2000);
        } catch (e) {
                alert(e);
        }
}

function check_win() {
        if (win) {
                var t = confirm("恭喜你通过本关，是否进行下一关？");
                if (t) {
                        window.location.href = "course1-9/course1-9-2.html";
                }
        }
        else {
                document.getElementById("hint").innerHTML = "再想想，有些地方不正确。";
        }
}

function reset() {
        dir = 1;
        desx = init_x;
        desy = init_y;
}